package customized_log

import (
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"os"
)

// Logger 定义日志接口
type Logger interface {
	Debug(args ...interface{})
	Debugf(template string, args ...interface{})
	Info(args ...interface{})
	Infof(template string, args ...interface{})
	Warn(args ...interface{})
	Warnf(template string, args ...interface{})
	Error(args ...interface{})
	Errorf(template string, args ...interface{})
	Sync() error
}

// CustomLogger 自定义日志结构体
type CustomLogger struct {
	sugarLogger *zap.SugaredLogger
}

func (l *CustomLogger) Debug(args ...interface{}) {
	l.sugarLogger.Debug(args...)
}

func (l *CustomLogger) Debugf(template string, args ...interface{}) {
	l.sugarLogger.Debugf(template, args...)
}

func (l *CustomLogger) Info(args ...interface{}) {
	l.sugarLogger.Info(args...)
}

func (l *CustomLogger) Infof(template string, args ...interface{}) {
	l.sugarLogger.Infof(template, args...)
}

func (l *CustomLogger) Warn(args ...interface{}) {
	l.sugarLogger.Warn(args...)
}

func (l *CustomLogger) Warnf(template string, args ...interface{}) {
	l.sugarLogger.Warnf(template, args...)
}

func (l *CustomLogger) Error(args ...interface{}) {
	l.sugarLogger.Error(args...)
}

func (l *CustomLogger) Errorf(template string, args ...interface{}) {
	l.sugarLogger.Errorf(template, args...)
}

func (l *CustomLogger) Sync() error {
	return l.sugarLogger.Sync()
}

var defaultLogger Logger

func GetLogger() Logger {
	if defaultLogger == nil {
		defaultLogger = NewCustomLogger()
	}
	return defaultLogger
}

func NewCustomLogger() Logger {
	writeSyncer := getLogWriter()
	encoder := getEncoder()
	core := zapcore.NewCore(encoder, writeSyncer, zapcore.DebugLevel)

	logger := zap.New(core, zap.AddCaller())
	sugarLogger := logger.Sugar()

	return &CustomLogger{
		sugarLogger: sugarLogger,
	}
}

func getEncoder() zapcore.Encoder {
	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
	encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
	return zapcore.NewConsoleEncoder(encoderConfig)
}

func getLogWriter() zapcore.WriteSyncer {
	file, _ := os.Create("./test.log")
	return zapcore.AddSync(file)
}
